import json

import cv2
import numpy as np


def match(screen_img):
    screen_img = cv2.imread(screen_img)
    end_img = cv2.imread('./image/end.png')
    screen_gray = cv2.cvtColor(screen_img, cv2.COLOR_BGR2GRAY)

    end_gray = cv2.cvtColor(end_img, cv2.COLOR_BGR2GRAY)
    endH, endW, c = end_img.shape

    result = cv2.matchTemplate(screen_gray, end_gray, cv2.TM_CCOEFF_NORMED)

    _, _, minLoc, maxLoc = cv2.minMaxLoc(result)

    # cv2.rectangle(screen_img, minLoc, (minLoc[0] + endW, minLoc[1] + endH), (0, 0, 255), 2)
    # screen_img = screen_img[0:minLoc[1], 0:minLoc[0]+endW]

    # cv2.imshow('Result', screen_img)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    # exit()

    tmpList = []
    for a in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
        target_img = './image/' + str(a) + '.png'

        # print('target_img:' + target_img)
        target_img = cv2.imread(target_img)
        target_gray = cv2.cvtColor(target_img, cv2.COLOR_BGR2GRAY)
        height, width, c = target_img.shape

        result = cv2.matchTemplate(screen_gray, target_gray, cv2.TM_CCOEFF_NORMED)

        threshold = 0.99  # 设置检测阈值

        loc = np.where(result >= threshold)  # 选取阈值大于0.8的

        for pt in zip(*loc[::-1]):
            one = {"no": a, "x": int(pt[0]) + int(width / 2), "y": int(pt[1]) + int(height / 2)}
            tmpList.append(one)
            cv2.rectangle(screen_img, pt, (pt[0] + width, pt[1] + height), (0, 0, 255), 2)
        # cv.imwrite('res.png', img_rgb)

        # for y in range(len(result)):
        #     for x in range(len(result[y])):
        #         if result[y][x] > 0.99:
        #             one = {"no": i, "x": x + int(width / 2), "y": y + int(height / 2)}
        #             tmpList.append(one)
        # cv2.rectangle(screen_img, (x, y), (x + width, y + height), (0, 0, 255), 2)

    # with open('grinding.json', 'w') as file:
    #     json.dump(tmpList, file)

    # cv2.imshow('Result', screen_img)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    # exit()
    return sort(tmpList)


def sort(tmpList):
    # with open('grinding.json', 'r') as f:
    #     tmpList = json.load(f)

    x_list = []
    x_list2 = []

    for i in tmpList:
        x_list.append(i["x"])

    x_list = sorted(set(x_list))

    for i in x_list:
        if not x_list2:
            x_list2.append(i)
        else:
            t = []
            for j in x_list2:
                t.append(abs(j - i) < 10)
            if True not in t:
                x_list2.append(i)

    r_list = []

    for j in x_list2:
        t = []
        for i in tmpList:
            if i['x'] == j or abs(i['x'] - j) < 10:
                t.append(i)
        t = y_sort(t)

        r_list.append(t)

    # for i in x_list:
    # with open('main.json', 'w') as file:
    #     json.dump(r_list, file)

    return r_list


def y_sort(list):
    t = []
    t1 = []
    for i in list:
        t.append(i['y'])
    t = sorted(set(t))
    for i in t:
        for j in list:
            if j['y'] == i:
                t1.append(j)
                break
    return t1
